# Copyright (C) 2007 Laszlo Pandy <laszlok2@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import sys
import gtk
import pango
import gtk.glade

from AdventureMoney.core import Utils
from AdventureMoney.core import Account
from AdventureMoney.store import Load
from AdventureMoney.store import Save
import InterfaceUtils
import ViewSwitcher

class AdventureGUI:
	
	__window_count = [0]
	
	def __init__(self, file=None):
		self.__window_count[0] += 1
		self.wTree = InterfaceUtils.GetGladeTree("MainWindow")
		
		signals = {
			"OnNew"			: self.OnNewFile,
			"OnOpen"		: self.OnOpenFile,
			"OnSave"		: self.OnSaveFile,
			"OnSaveAs"		: self.OnSaveFileAs,
			"OnQuit"		: self.OnQuit,
			"OnViewMoneyOwed"	: self.OnViewMoneyOwed,
			"OnViewSummary"		: self.OnViewSummary,
			"OnViewPayments"	: self.OnViewPayments,
			"OnViewPeople"		: self.OnViewPeople,
			"OnViewCategories"	: self.OnViewCategories,
			"OnNewWindow"		: self.OnNewWindow,
			"OnAbout"		: self.OnAbout,
		}
		
		self.wTree.signal_autoconnect(signals)
		
		self.settingButtons = False
		self.window = self.wTree.get_widget("MainWindow")
		self.mainVBox = self.wTree.get_widget("MainVBox")
		self.viewSwitcher = None
		
		self.owedRadio = self.wTree.get_widget("MoneyOwedRadio")
		self.summaryRadio = self.wTree.get_widget("SummaryRadio")
		self.paymentRadio = self.wTree.get_widget("PaymentRadio")
		self.categoryRadio = self.wTree.get_widget("CategoryRadio")
		self.peopleRadio = self.wTree.get_widget("PeopleRadio")
		
		self.buttonDict = {
			"owed" : self.owedRadio,
			"summary" : self.summaryRadio,
			"payment" : self.paymentRadio,
			"category" : self.categoryRadio,
			"people" : self.peopleRadio
		}
		
		self.LoadAccount(file)
		self.window.show_all()
		
	def LoadAccount(self, file):
		self.file = file
		
		self.staticAccount = None
		if file:
			self.account = Load.LoadFromPath(file)
			if not self.account:
				dlg = gtk.MessageDialog(self.window,
				        gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
				        gtk.MESSAGE_ERROR,
				        gtk.BUTTONS_OK,
				        "This file was created with a newer version of Adventure Money")
				dlg.run()
				dlg.destroy()
				return
		else:
			self.account = Account.Account()
			self.account.addPerson("Manager")
		
		self.staticAccount = self.account.copy()
		
		if self.viewSwitcher:
			self.mainVBox.remove(self.viewSwitcher)
			self.viewSwitcher.disconnect_by_func(self.OnViewChanged)
		
		self.viewSwitcher = ViewSwitcher.ViewSwitcherVBox(self.window, self.account)
		self.viewSwitcher.connect("view-changed", self.OnViewChanged)
		self.mainVBox.pack_end(self.viewSwitcher)
		#notify the GUI to load everything
		self.account.emit("loaded")
		
	def OnNewFile(self, widget=None):
		AdventureGUI().window.present()
	
	def OnOpenFile(self, widget=None):
		chooser = gtk.FileChooserDialog("Choose an account file", self.window, 
				gtk.FILE_CHOOSER_ACTION_OPEN,
				(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))

		chooser.set_default_response(gtk.RESPONSE_OK)
		chooser.set_transient_for(self.window)
		
		allfilter = gtk.FileFilter()
		allfilter.set_name("All Files")
		allfilter.add_pattern("*")
		
		jokfilter = gtk.FileFilter()
		jokfilter.set_name("Adventure Account File (*.adventure)")
		jokfilter.add_pattern("*.adventure")
		
		chooser.add_filter(jokfilter)
		chooser.add_filter(allfilter)
		
		response = chooser.run()
		
		if response == gtk.RESPONSE_OK:
			
			filename = chooser.get_filename()
			#if there is no file, and no changes, the account is empty
			if not self.file and self.staticAccount == self.account:
				self.LoadAccount(filename)
			else:
				AdventureGUI(filename).window.present()
			
		#elif response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
			#break

		chooser.destroy()
	
	def OnSaveFile(self, widget=None):
		if self.file:
			Save.SaveToPath(self.file, self.account)
			self.staticAccount = self.account.copy()
			return 0
		else:
			return self.OnSaveFileAs()
	
	def OnSaveFileAs(self, widget=None):
		chooser = gtk.FileChooserDialog("Choose the filename to save the account", self.window,
				gtk.FILE_CHOOSER_ACTION_SAVE,
				(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK))
		chooser.set_do_overwrite_confirmation(True)
		if self.file:
			chooser.set_current_name(self.file)
		chooser.set_default_response(gtk.RESPONSE_OK)
		#chooser.set_current_folder(Globals.settings.general["projectfolder"])

		response = chooser.run()
		if response == gtk.RESPONSE_OK:
			self.file = chooser.get_filename()
			#Globals.settings.general["projectfolder"] = os.path.dirname(filename)
			#Globals.settings.write()
			Save.SaveToPath(self.file, self.account)
			self.staticAccount = self.account.copy()
			chooser.destroy()
			return 0
		else:
			chooser.destroy()
			return 1
	
	def OnQuit(self, widget, event=None):
		while self.staticAccount != self.account:
			msg1 = "Save changes to the account before closing?"
			msg2 = "Your changes will be lost if you don't save them."
			message = "<span size='large' weight='bold'>%s</span>\n\n%s" % (msg1, msg2)
			
			dlg = gtk.MessageDialog(self.window,
				gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
				gtk.MESSAGE_WARNING,
				gtk.BUTTONS_NONE)
			dlg.set_markup(message)
			
			dlg.add_button("Close _Without Saving", gtk.RESPONSE_NO)
			dlg.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
			defaultAction = dlg.add_button(gtk.STOCK_SAVE, gtk.RESPONSE_YES)
			#make save the default action when enter is pressed
			dlg.set_default(defaultAction)
			
			dlg.set_transient_for(self.window)
			
			response = dlg.run()
			dlg.destroy()
			if response == gtk.RESPONSE_YES:
				if self.OnSaveFile() == 0:
					break
			elif response == gtk.RESPONSE_NO:
				break
			elif response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
				return 1
		
		self.window.destroy()
		self.__window_count[0] -= 1
		if self.__window_count[0] <= 0:
			gtk.main_quit()
		
	def OnViewChanged(self, widget):
		string = self.viewSwitcher.GetCurrentViewString()
		
		self.settingButtons = True
		for name, button in self.buttonDict.iteritems():
			button.set_active(name == string)
		self.settingButtons = False
	
	def OnViewMoneyOwed(self, widget):
		if not self.settingButtons:
			self.viewSwitcher.OnOwedView()
	
	def OnViewSummary(self, widget):
		if not self.settingButtons:
			self.viewSwitcher.OnSummaryView()
	
	def OnViewPayments(self, widget):
		if not self.settingButtons:
			self.viewSwitcher.OnPaymentView()
		
	def OnViewPeople(self, widget):
		if not self.settingButtons:
			self.viewSwitcher.OnPeopleView()
		
	def OnViewCategories(self, widget):
		if not self.settingButtons:
			self.viewSwitcher.OnCategoryView()
		
	def OnNewWindow(self, widget):
		AlternateWindow(self.account)
		
	def OnAbout(self, widget):
		tree = InterfaceUtils.GetGladeTree("AboutDialog")
		tree.signal_autoconnect({"AboutDialogClose" : self.CloseAboutDialog})
		
	def CloseAboutDialog(self, widget, event):
		widget.destroy()

class AlternateWindow(gtk.Window):
	def __init__(self, account):
		gtk.Window.__init__(self)
		self.vbox = ViewSwitcher.ViewSwitcherVBox(self, account)
		self.vbox.OnAccountLoaded()
		self.add(self.vbox)
		self.show_all()
